<?php
namespace app\admin\controller;
/**
 * 保险控制
 */
class Insurance extends Common
{
	public function index()
	{

		if(request()->isPost())
		{
            $insurance = db('insurance');

            $list = $insurance
            ->alias('i')
            ->join('loan l','i.type = l.id')
            ->field('i.*,l.typename')
            ->order('sort')
            ->select();
            // print_r( $list);die;
            foreach ($list as $key => $value) {
                $list[$key]['rate']=$value['rate']*100;
            }

            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        }
        $this->assign('typename',$typename);
		return $this->fetch();
	} 

 
	public function add()
	{
        $loan=db('loan')->select();
		if(request()->isPost())
		{
            $data = input('post.');
            $data['rate']=$data['rate']*0.01;
            $info = db('insurance') -> insert($data);
            if ($info)
            {
            	$result['msg'] = '添加保险成功!';
	            $result['url'] = url('index');
	            $result['code'] = 1;
            } else 
            {
            	$result['msg'] = '添加保险失败!';
	            $result['url'] = url('add');
	            $result['code'] = 0;
            }
            return $result;
        }
        $this->assign('loan',$loan);
		return $this->fetch();
	}

	public function del()
	{
        $id = input('id');
        if (empty($id)){
            return ['code'=>0,'msg'=>'保险ID不存在！'];
        }
        db('insurance')->where(array('id'=>$id))->delete();
        return ['code'=>1,'msg'=>'删除成功！'];
    }

    public function edit()
    {
        $loan=db('loan')->select();
        if(request()->isPost()) 
        {
            $data = input('post.');
            $data['rate']=$data['rate']*0.01;
            db('insurance')->update($data);
            $result['msg'] = '修改成功!';
            $result['url'] = url('index');
            $result['code'] = 1;
            return $result;
        } else
        {
            $map['id'] = input('param.id');
            $info = db('insurance')->where($map)->find();

                $info['rate']=$info['rate']*100;

            $this->assign('title',lang('edit')."种类");
            $this->assign('info',$info);
            $this->assign('loan',$loan);
            return $this->fetch();
        }
    }

    public function open($value='')
    {
        $id=input('post.id');
        $open=input('post.open');
        if(db('insurance')->where('id='.$id)->update(['open'=>$open])!==false){
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }


    public function order()
    {
        $data = input('post.');
        db('insurance')->update($data);
        $result['msg'] = '排序更新成功!';
        $result['url'] = url('index');
        $result['code'] = 1;
        return $result;
    }    

}